<template>
<div class="container mx-auto p-4 overflow-y-auto">
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold text-gray-800">
        {{ isCreate ? t('创建电池护照') : t('编辑电池护照') }}
      </h1>
      <div>
        <el-button @click="goBack">{{ t('取消') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ t('保存') }}</el-button>
      </div>
    </div>
    <el-form ref="formRef" :model="formData" label-position="left">
      <el-collapse v-model="activeNames" accordion expand-icon-position='left'>
        <!-- 基本信息 -->
        <el-collapse-item :title="t('标识符和产品数据')" name="generalInfo">

          <CustomInput
              v-model="formData.generalInfo.productIdentifier"
              :label="t('电池标识符')"
              :desc="t('电池标识符是用于识别电池的唯一字符串，该字符串还支持链接到电池护照')"
          />

          <CustomInput
            v-model="formData.generalInfo.batteryPassportIdentifier"
            :label="t('电池护照标识符')"
            :desc="t('电池护照标识符是电池护照的唯一标识符')"
          />

          <CustomInput
              v-model="formData.generalInfo.batteryCategory"
              :label="t('电池类别')"
              :desc="t('电池的预期用途，如电动汽车电池、工业电池、轻型运输工具电池等。')"
              component="select"
              :enumList="BatteryCategory"
          />

          <CustomInput
              v-model="formData.generalInfo.manufacturerInformation.identifier"
              :label="t('制造商标识符和信息')"
              :desc="t('制造商信息应包括：名称；注册商号或注册商标；邮政地址（注明单一联系点）；网站地址（如有）；电子邮件地址（如有）。')"
          />

          <CustomInput
              v-model="formData.generalInfo.manufacturerInformation.contactName"
              :label="t('制造商名称')"
          />

          <CustomInput
              v-model="formData.generalInfo.manufacturerInformation.emailAddress"
              :label="t('制造商邮箱')"
              type="email"
          />

          <CustomInput
              v-model="formData.generalInfo.manufacturerInformation.webAddress"
              :label="t('制造商网站')"
          />

          <CustomInput
              v-model="formData.generalInfo.manufacturerInformation.postalAddress"
              component="address"
              :label="t('制造商地址')"
          />

          <CustomInput
              v-model="formData.generalInfo.manufacturingDate"
              :label="t('投入使用日期')"
              :desc="t('电池投入使用日期，一般以BMS记录的投入使用日期为准，以年份和月份表示。一般适用于使用BMS的SBESS和LMT电池。')"
              component="date-picker"
              format="YYYY-MM"
              valueFormat="YYYY-MM-DD HH:mm:ss"
              type="month"
          />

          <CustomInput
              v-model="formData.generalInfo.batteryStatus"
              :label="t('电池状态')"
              :desc="t('电池在其生命周期中的即时状态，定义为新电池、梯次利用、再利用、再制造或废电池。')"
              component="select"
              :enumList="BatteryCategory"
          />

          <CustomInput
              v-model="formData.generalInfo.batteryMass"
              :label="t('电池质量')"
              :desc="t('电池的物理重量')"
              component="CustomNumber"
              unit="[KG]"
              :precision="2"
          />

          <CustomInput
              v-model="formData.generalInfo.manufacturingPlace"
              component="address"
              :label="t('制造地点')"
              :desc="t('电池制造工厂的地理位置。')"
          />

          <CustomInput
              v-model="formData.generalInfo.operatorInformation.identifier"
              :label="t('经济运营商标识符和信息')"
              :desc="t('运营商信息应包括：名称；注册商号或注册商标；邮政地址（注明单一联系点）；网站地址（如有）；电子邮件地址（如有）')"
          />

          <CustomInput
            v-model="formData.generalInfo.operatorInformation.contactName"
            :label="t('运营商名称')"
          />

          <CustomInput
            v-model="formData.generalInfo.operatorInformation.emailAddress"
            :label="t('运营商邮箱')"
            type="email"
          />

          <CustomInput
            v-model="formData.generalInfo.operatorInformation.webAddress"
            :label="t('运营商网站')"
          />
          
          <CustomInput
            v-model="formData.generalInfo.operatorInformation.postalAddress"
            component="address"
            :label="t('运营商地址')"
          />

          <CustomInput
              v-model="formData.generalInfo.puttingIntoService"
              :label="t('交付使用')"
          />

          <CustomInput
            v-model="formData.generalInfo.warrentyPeriod"
            :label="t('保修期')"
            :desc="t('电池的商业保修期，以年份和月份表示。')"
          />

        </el-collapse-item>

        <el-collapse-item name="labelsConformity" :title="t('符号、标签、符合性声明文档')">

          <CustomInput
            v-model="formData.labelsConformity.declarationOfConformity"
            :label="t('欧盟符合性声明')"
            :desc="t('声明符合欧盟要求并承担责任的文件应上传到电池护照中。（ID、CE 标志）')"
            component="file"
          />

          <CustomInput
            v-model="formData.labelsConformity.resultOfTestReport"
            :label="t('测试报告或合规证明材料')"
            :desc="t('可以证明符合电池法规中规定的要求的测试报告结果')"
            component="file"
          />

          <CustomInput
            v-model="formData.labelsConformity.labels"
            :label="t('分类回收符号')"
            :desc="t('表示该产品必须被送往独立的收集设施进行回收和再循环的符号。')"
            :columns="labelColumns"
            :default-item="defaultLabel"
            component="table"
            :add-button-text="t('添加标签')"
          />
        </el-collapse-item>

        <!-- 电池材料和组成 -->
        <el-collapse-item name="materialComposition" :title="t('电池材料和组成')">
          <CustomInput
            v-model="formData.materialComposition.batteryChemistry.shortName"
            :label="t('简称')"
          />

          <CustomInput
            v-model="formData.materialComposition.batteryChemistry.clearName"
            :label="t('全称')"
          />

          <CustomInput
            v-model="formData.materialComposition.batteryMaterials"
            :label="t('电池化学体系')"
            :desc="t('电池化学成分应与电池的阴极、阳极和电解质的命名有关。（指电池内部所用的材料经过化学反应的组成）')"
            component="table"
            :columns="materialColumns"
            :default-item="defaultMaterial"
          />

          <CustomInput
            v-model="formData.materialComposition.hazardousSubstances"
            :label="t('有害物质')"
            :desc="t('除汞、镉、铅之外，对人类健康和环境构成威胁的物质。')"
            component="table"
            :columns="substanceColumns"
            :default-item="defaultSubstance"
          />
        </el-collapse-item>

        <!-- 碳足迹 -->
        <el-collapse-item name="carbonFootprint" :title="t('电池碳足迹')">
          <CustomInput
            v-model="formData.carbonFootprint.batteryCarbonFootprint"
            :label="t('单位能量碳足迹')"
            :desc="t('电池在生命周期内产生的总二氧化碳排放当量除以电池预期使用寿命内输出总能量（以kWh为单位）的值，以kg CO2e/kWh计。')"
            component="CustomNumber"
            unit="kg/CO2e"
            :precision="2"
          />

          <CustomInput
            v-model="formData.carbonFootprint.carbonFootprintPerformanceClass"
            :label="t('碳足迹性能等级')"
            :desc="t('每个制造工厂生产的特定电池型号对应的碳足迹性能等级。')"
          />

          <CustomInput
            v-model="formData.carbonFootprint.carbonFootprintStudy"
            :desc="t('碳足迹研究报告的公开版本访问链接。')"
            :label="t('碳足迹研究报告链接')"
            component="file"
          />
          
          <CustomInput
            v-model="formData.carbonFootprint.carbonFootprintPerLifecycleStage"
            :label="t('生产阶段的单位能量碳足迹')"
            :desc="t('电池在生产阶段产生的二氧化碳排放当量除以电池预期使用寿命内输出总能量（以kWh为单位）的值，以kg CO2e/kWh计。电池生产阶段是指原材料获取和预处理阶段结束后，原材料进入电池单体生产制造，直至形成电池包或电池系统的过程。')"
            component="table"
            :columns="stageColumns"
            :default-item="defaultStage"
          />
        </el-collapse-item>
        
        <!-- 性能数据 -->
        <el-collapse-item name="performanceData" :title="t('性能和耐久性')">
          <!-- 电池技术属性 -->
          <CustomInput
            v-model="formData.performanceData.batteryTechicalProperties.ratedCapacity"
            :label="t('额定容量')"
            :desc="t('以制造商规定的条件测得的并由制造商声明的电池容量值，以安时（Ah）或毫安时（mAh）表示。')"
            component="CustomNumber"
            unit="Ah"
            :precision="2"
          />

          <CustomInput
            v-model="formData.performanceData.batteryTechicalProperties.ratedEnergy"
            :label="t('额定能量')"
            component="CustomNumber"
            unit="kWh"
            :precision="2"
          />

          <CustomInput
            v-model="formData.performanceData.batteryTechicalProperties.ratedMaximumPower"
            :label="t('额定最大功率')"
            component="CustomNumber"
            unit="kW"
            :precision="2"
          />

          <CustomInput
            v-model="formData.performanceData.batteryTechicalProperties.nominalVoltage"
            :label="t('标称电压')"
            :desc="t('由厂家指定的用以标识符电池的适宜的电压近似值，以伏特（V）表示。')"
            component="CustomNumber"
            unit="V"
            :precision="2"
          />

          <CustomInput
            v-model="formData.performanceData.batteryTechicalProperties.minimumVoltage"
            :label="t('最小电压')"
            :desc="t('在制造商指定的温度区间内，制造商规定的正常放电时的最小电压，以伏特（V）表示。')"
            component="CustomNumber"
            unit="V"
            :precision="2"
          />

          <CustomInput
            v-model="formData.performanceData.batteryTechicalProperties.maximumVoltage"
            :label="t('最大电压')"
            :desc="t('在制造商指定的温度区间内，制造商规定的正常充电时的最大电压，以伏特（V）表示。')"
            component="CustomNumber"
            unit="V"
            :precision="2"
          />

          <CustomInput
            v-model="formData.performanceData.batteryTechicalProperties.initialSelfDischarge"
            :label="t('初始自放电率')"
            :desc="t('自放电指电池内部自发的或不期望的化学反应造成可用容量自动减少的现象。初始自放电率指电池在初始状态下，在规定的条件下测得的容量减少率，以百分比/月（%/月）表示。一般适用于使用BMS的SBESS和LMT电池。')"
            component="CustomNumber"
            unit="%/月"
            :precision="2"
          />

          <CustomInput
            v-model="formData.performanceData.batteryTechicalProperties.roundtripEfficiency"
            :label="t('往返效率')"
            component="CustomNumber"
            unit="%"
            :precision="2"
          />

          <CustomInput
            v-model="formData.performanceData.batteryTechicalProperties.expectedNumberOfCycles"
            :label="t('预期循环次数')"
            component="CustomNumber"
          />

          <CustomInput
            v-model="formData.performanceData.batteryTechicalProperties.expectedLifetime"
            :label="t('预期寿命（日历年限）')"
            component="CustomNumber"
            :unit="t('年')"
            :precision="1"
          />

          <CustomInput
            v-model="formData.performanceData.batteryTechicalProperties.capacityThresholdForExhaustion"
            :label="t('容量衰减阈值')"
            component="CustomNumber"
            unit="%"
          />

          <CustomInput
            v-model="formData.performanceData.batteryTechicalProperties.crate"
            :label="t('C-rate')"
            component="CustomNumber"
            :precision="2"
          />

          <CustomInput
            v-model="formData.performanceData.batteryTechicalProperties.crateLifeCycleTest"
            :label="t('生命周期测试C-rate')"
            component="CustomNumber"
            :precision="2"
          />

          <CustomInput
            v-model="formData.performanceData.batteryTechicalProperties.lifetimeReferenceTest"
            :label="t('寿命参考测试')"
            component="file"
          />

          <CustomInput
            v-model="formData.performanceData.batteryTechicalProperties.temperatureRangeIdleState"
            :label="t('闲置状态温度范围')"
            component="CustomNumber"
            unit="°C"
            :min="-40"
          />

          <CustomInput
            v-model="formData.performanceData.batteryTechicalProperties.originalPowerCapability"
            :label="t('原始功率能力')"
            component="table"
            :columns="powerCapabilityColumns"
            :default-item="defaultPowerCapability"
          />
          
          <CustomInput
            v-model="formData.performanceData.batteryTechicalProperties.initialInternalResistance"
            :label="t('初始内阻')"
            component="table"
            :columns="resistanceColumns"
            :default-item="defaultResistance"
          />

          <!-- 电池状态 -->
          <CustomInput
            v-model="formData.performanceData.batteryCondition.energyThroughput"
            :label="t('能量吞吐量')"
            component="CustomNumber"
            unit="kWh"
            :precision="2"
          />

          <CustomInput
            v-model="formData.performanceData.batteryCondition.powerFade"
            :label="t('功率衰减')"
            component="CustomNumber"
            unit="%"
          />

          <CustomInput
            v-model="formData.performanceData.batteryCondition.roundTripEfficiencyFade"
            :label="t('往返效率衰减')"
            component="CustomNumber"
            unit="%"
          />

          <CustomInput
            v-model="formData.performanceData.batteryCondition.evolutionOfSelfDischarge"
            :label="t('自放电演变')"
            component="CustomNumber"
            unit="%"
          />

          <CustomInput
            v-model="formData.performanceData.batteryCondition.roundTripEfficiencyat50PerCentCycleLife"
            :label="t('50%循环寿命时的往返效率')"
            component="CustomNumber"
            unit="%"
          />

          <CustomInput
            v-model="formData.performanceData.batteryCondition.capacityThroughput"
            :label="t('容量吞吐量')"
            component="value-with-date"
            value-key="value"
            date-key="lastUpdate"
            :precision="2"
          />

          <CustomInput
            v-model="formData.performanceData.batteryCondition.numberOfFullCycles"
            :label="t('完整循环次数')"
            component="value-with-date"
            value-key="value"
            date-key="lastUpdate"
          />

          <CustomInput
            v-model="formData.performanceData.batteryCondition.stateOfCertifiedEnergy"
            :label="t('认证能量状态')"
            component="value-with-date"
            value-key="value"
            date-key="lastUpdate"
            unit="%"
          />

          <CustomInput
            v-model="formData.performanceData.batteryCondition.capacityFade"
            :label="t('容量衰减')"
            component="value-with-date"
            value-key="value"
            date-key="lastUpdate"
            unit="%"
          />

          <CustomInput
            v-model="formData.performanceData.batteryCondition.remainingEnergy"
            :label="t('剩余能量')"
            component="value-with-date"
            value-key="value"
            date-key="lastUpdate"
            unit="%"
          />

          <CustomInput
            v-model="formData.performanceData.batteryCondition.remainingCapacity"
            :label="t('剩余容量')"
            component="value-with-date"
            value-key="value"
            date-key="lastUpdate"
            unit="%"
          />

          <CustomInput
            v-model="formData.performanceData.batteryCondition.currentSelfDischargingRate"
            :label="t('当前自放电率')"
            component="value-with-date"
            value-key="value"
            date-key="lastUpdate"
            unit="%/月"
            :precision="2"
          />

          <CustomInput
            v-model="formData.performanceData.batteryCondition.remainingRoundTripEnergyEfficiency"
            :label="t('剩余往返能量效率')"
            component="value-with-date"
            value-key="value"
            date-key="lastUpdate"
            unit="%"
          />

          <CustomInput
            v-model="formData.performanceData.batteryCondition.stateOfCharge"
            :label="t('充电状态')"
            component="value-with-date"
            value-key="value"
            date-key="lastUpdate"
            unit="%"
          />

          <!-- 温度信息 -->
          <CustomInput
            v-model="formData.performanceData.batteryCondition.temperatureInformation.timeExtremeHighTemp"
            :label="t('极端高温时间')"
            component="CustomNumber"
            unit="小时"
          />

          <CustomInput
            v-model="formData.performanceData.batteryCondition.temperatureInformation.timeExtremeLowTemp"
            :label="t('极端低温时间')"
            component="CustomNumber"
            unit="小时"
          />

          <CustomInput
            v-model="formData.performanceData.batteryCondition.temperatureInformation.timeExtremeHighTempCharging"
            :label="t('充电时极端高温时间')"
            component="CustomNumber"
            unit="小时"
          />

          <CustomInput
            v-model="formData.performanceData.batteryCondition.temperatureInformation.timeExtremeLowTempCharging"
            :label="t('充电时极端低温时间')"
            component="CustomNumber"
            unit="小时"
          />

          <CustomInput
            v-model="formData.performanceData.batteryCondition.temperatureInformation.lastUpdate"
            :label="t('温度信息最后更新时间')"
            component="date-picker"
            type="datetime"
            valueFormat="YYYY-MM-DD HH:mm:ss"
          />

          <CustomInput
            v-model="formData.performanceData.batteryCondition.remainingPowerCapability"
            :label="t('剩余功率能力')"
            component="table"
            :columns="powerCapabilityColumns"
            :default-item="defaultPowerCapability"
          />
          
          <CustomInput
            v-model="formData.performanceData.batteryCondition.internalResistanceIncrease"
            :label="t('内阻增加')"
            component="table"
            :columns="resistanceColumns"
            :default-item="defaultResistance"
          />
          
          <CustomInput
            v-model="formData.performanceData.batteryCondition.negativeEvents"
            :label="t('负面事件')"
            component="table"
            :columns="negativeEventColumns"
            :default-item="defaultNegativeEvent"
          />
        </el-collapse-item>
        
        <!-- 循环信息 -->
        <el-collapse-item name="circularityInfo" :title="t('循环信息')">
          <CustomInput
            v-model="formData.circularityInfo.dismantlingAndRemovalInformation"
            :label="t('拆卸和移除信息')"
            component="table"
            :columns="documentColumns"
            :default-item="defaultDocument"
          />
          
          <CustomInput
            v-model="formData.circularityInfo.sparePartSources"
            :label="t('备件来源')"
            component="table"
            :columns="supplierColumns"
            :default-item="defaultSupplier"
          />
          
          <CustomInput
            v-model="formData.circularityInfo.recycledContent"
            :label="t('回收内容')"
            component="table"
            :columns="recycledContentColumns"
            :default-item="defaultRecycledContent"
          />

          <CustomInput
            v-model="formData.circularityInfo.safetyMeasures.safetyInstructions"
            :label="t('安全说明')"
            component="file"
          />

          <CustomInput
            v-model="formData.circularityInfo.safetyMeasures.extinguishingAgent"
            :label="t('灭火剂')"
            component="select"
            :enumList="ExtinguishingAgentType"
            multiple
          />

          <CustomInput
            v-model="formData.circularityInfo.endOfLifeInformation.wastePrevention"
            :label="t('废物预防')"
            component="file"
          />

          <CustomInput
            v-model="formData.circularityInfo.endOfLifeInformation.separateCollection"
            :label="t('分类收集')"
            component="file"
          />

          <CustomInput
            v-model="formData.circularityInfo.endOfLifeInformation.informationOnCollection"
            :label="t('收集信息')"
            component="file"
          />

          <CustomInput
            v-model="formData.circularityInfo.renewableContent"
            :label="t('可再生内容')"
            component="CustomNumber"
            unit="%"
          />
        </el-collapse-item>
        
        <!-- 供应链 -->
        <el-collapse-item name="supplyChain" :title="t('供应链尽职调查')">
          <CustomInput
            v-model="formData.supplyChain.supplyChainDueDiligenceReport"
            :label="t('尽职调查报告')"
            :desc="t('尽职调查报告是关于供应链尽职调查政策、风险管理计划和第三方验证摘要（“尽职调查报告”）的报告')"
            component="file"
          />

          <CustomInput
            v-model="formData.supplyChain.thirdPartyAssurances"
            :label="t('第三方认可计划保证（如证书）')"
            :desc="t('作为非强制性数据属性，电池护照应包含有关第三方供应链保证的信息，例如认证、公认的供应链计划')"
            component="file"
          />

          <CustomInput
            v-model="formData.supplyChain.supplyChainIndices"
            :label="t('供应链指数')"
            :desc="t('作为非强制性数据属性，电池护照应包含供应链指数，以便消费者轻松评估负责任采购的水平')"
            component="CustomNumber"
          />
        </el-collapse-item>
      </el-collapse>
    </el-form>
  </div>
</template>
<script setup>
import {computed, onMounted, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import batteryPassportApi from '@/api/batteryPassport'
import {ElMessage} from 'element-plus'
import {batteryPassportDetail} from "@/router/index.js";
import {
  BatteryCategory,
  BatteryComponent,
  ExtinguishingAgentType,
  hazardousSubstanceClassType,
  LifecycleStage,
  RecycledMaterialType
} from "@/api/_const.js";
import CustomInput from "@/views/BatteryPassport/components/CustomInput.vue";
import {useI18n} from "vue-i18n";

const {t} = useI18n()

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const formData = ref(
    {
      "generalInfo": {
        "productIdentifier": "LN-X1-C8-BLA",
        "batteryPassportIdentifier": "PTL-BXS-202509002",
        "batteryCategory": "lmt",
        "manufacturerInformation": {
          "contactName": "",
          "postalAddress": {
            "addressCountry": "",
            "streetAddress": "深圳市宝安区石岩街道上屋社区爱群路同富裕工业区4-7#厂房一层-五层",
            "postalCode": ""
          },
          "identifier": "LNBD-C-B8-2025Q3-00123456",
          "emailAddress": "",
          "webAddress": ""
        },
        "manufacturingDate": "2025-09-01 00:00:00",
        "batteryStatus": null,
        "batteryMass": 0.5,
        "manufacturingPlace": {
          "addressCountry": "",
          "streetAddress": "",
          "postalCode": ""
        },
        "operatorInformation": {
          "contactName": "",
          "postalAddress": {
            "addressCountry": "",
            "streetAddress": "",
            "postalCode": ""
          },
          "identifier": "",
          "emailAddress": "",
          "webAddress": ""
        },
        "puttingIntoService": "",
        "warrentyPeriod": ""
      },
      "materialComposition": {
        "batteryChemistry": {
          "shortName": "NCM",
          "clearName": "锂镍锰钴氧化物"
        },
        "batteryMaterials": [
          {
            "batteryMaterialLocation": {
              "componentName": null,
              "componentId": null
            },
            "batteryMaterialIdentifier": null,
            "batteryMaterialName": "钴、锂、镍、天然石墨",
            "batteryMaterialMass": null,
            "isCriticalRawMaterial": null
          }
        ],
        "hazardousSubstances": [
          {
            "hazardousSubstanceClass": "AcuteToxicity",
            "hazardousSubstanceName": "钴",
            "hazardousSubstanceConcentration": null,
            "hazardousSubstanceImpact": [],
            "hazardousSubstanceLocation": {
              "componentName": "电解液",
              "componentId": "ELY-001"
            },
            "hazardousSubstanceIdentifier": "2632-16-1"
          }
        ]
      },
      "carbonFootprint": {
        "batteryCarbonFootprint": null,
        "carbonFootprintPerLifecycleStage": [],
        "carbonFootprintPerformanceClass": "",
        "carbonFootprintStudy": ""
      },
      "performanceData": {
        "batteryTechicalProperties": {
          "originalPowerCapability": [],
          "ratedMaximumPower": null,
          "powerCapabilityRatio": null,
          "ratedEnergy": null,
          "expectedNumberOfCycles": null,
          "initialSelfDischarge": null,
          "roundtripEfficiency": null,
          "ratedCapacity": 8,
          "initialInternalResistance": [],
          "expectedLifetime": null,
          "nominalVoltage": null,
          "minimumVoltage": null,
          "maximumVoltage": null,
          "capacityThresholdForExhaustion": null,
          "lifetimeReferenceTest": "",
          "temperatureRangeIdleState": null,
          "crate": null,
          "crateLifeCycleTest": null
        },
        "batteryCondition": {
          "energyThroughput": null,
          "capacityThroughput": {
            "value": null,
            "lastUpdate": null
          },
          "numberOfFullCycles": {
            "value": null,
            "lastUpdate": null
          },
          "stateOfCertifiedEnergy": {
            "value": null,
            "lastUpdate": null
          },
          "capacityFade": {
            "value": null,
            "lastUpdate": null
          },
          "remainingEnergy": {
            "value": null,
            "lastUpdate": null
          },
          "remainingCapacity": {
            "value": null,
            "lastUpdate": null
          },
          "negativeEvents": [],
          "temperatureInformation": {
            "timeExtremeHighTemp": null,
            "timeExtremeLowTemp": null,
            "timeExtremeHighTempCharging": null,
            "timeExtremeLowTempCharging": null,
            "lastUpdate": null
          },
          "remainingPowerCapability": [],
          "powerFade": null,
          "roundTripEfficiencyFade": null,
          "evolutionOfSelfDischarge": null,
          "currentSelfDischargingRate": {
            "value": null,
            "lastUpdate": null
          },
          "internalResistanceIncrease": [],
          "roundTripEfficiencyat50PerCentCycleLife": null,
          "remainingRoundTripEnergyEfficiency": {
            "value": null,
            "lastUpdate": null
          },
          "stateOfCharge": {
            "value": null,
            "lastUpdate": null
          }
        }
      },
      "circularityInfo": {
        "dismantlingAndRemovalInformation": [],
        "sparePartSources": [],
        "recycledContent": [],
        "safetyMeasures": {
          "safetyInstructions": "http://xxx.com",
          "extinguishingAgent": []
        },
        "endOfLifeInformation": {
          "wastePrevention": "http://xxx.com",
          "separateCollection": "http://xxx.com",
          "informationOnCollection": "http://xxx.com"
        },
        "renewableContent": null
      },
      "labelsConformity": {
        "declarationOfConformity": "http://xxx.com",
        "resultOfTestReport": "",
        "labels": [
          {
            "labelingSymbol": "http://xxx.com",
            "labelingMeaning": {
              "zh": "不可回收标志",
              "en": "不可回收标志"
            },
            "labelingSubject": "SeparateCollection"
          },
          {
            "labelingSymbol": "http://xxx.com",
            "labelingMeaning": {
              "zh": "不可充电",
              "en": "不可充电"
            },
            "labelingSubject": "SeparateCollection"
          },
          {
            "labelingSymbol": "http://xxx.com",
            "labelingMeaning": {
              "zh": "铅",
              "en": "铅"
            },
            "labelingSubject": "HazardousMaterial"
          },
          {
            "labelingSymbol": "http://xxx.com",
            "labelingMeaning": {
              "zh": "镉",
              "en": "镉"
            },
            "labelingSubject": "HazardousMaterial"
          },
          {
            "labelingSymbol": "http://xxx.com",
            "labelingMeaning": {
              "zh": "灭火剂",
              "en": "灭火剂"
            },
            "labelingSubject": "ExtinguishingAgent"
          }
        ]
      },
      "supplyChain": {
        "supplyChainDueDiligenceReport": "http://xxx.com",
        "thirdPartyAssurances": "",
        "supplyChainIndices": null
      },
      "createdAt": null,
      "updatedAt": null
    }
)
const loading = ref(true)
const activeNames = ref(['generalInfo'])// 表单验证规则

// 标签合规 - 标签列配置
const labelColumns = ref([
  {prop: 'labelingSymbol', label: t('标签符号'), type: 'input', component: 'file'},
  {prop: 'labelingSubject', label: t('标签主题'), type: 'select', options: LifecycleStage},
  {
    prop: 'labelingMeaning',
    label: t('标签含义'),
    type: 'complex',
    children: [
      {prop: 'en', placeholder: t('说明1'), type: 'input'},
      {prop: 'zh', placeholder: t('说明2'), type: 'input'}
    ]
  }
])
const defaultLabel = ref({
  labelingSymbol: '',
  labelingSubject: '',
  labelingMeaning: {en: '', zh: '', fr: ''}
}) // 材料组成 - 电池材料列配置
const materialColumns = ref([
  {prop: 'batteryMaterialName', label: t('材料名称'), type: 'input'},
  {prop: 'batteryMaterialIdentifier', label: t('材料标识符'), type: 'input'},
  {prop: 'batteryMaterialMass', label: t('材料质量(kg)'), type: 'input-number', min: 0, precision: 3},
  {prop: 'isCriticalRawMaterial', label: t('关键原材料'), type: 'switch'},
  {
    prop: 'batteryMaterialLocation',
    label: t('所在组件'),
    type: 'complex',
    children: [
      {prop: 'componentName', placeholder: t('组件名称'), type: 'input'},
      {prop: 'componentId', placeholder: t('组件ID'), type: 'input'}]
  }
])
const defaultMaterial = ref({
  batteryMaterialName: '',
  batteryMaterialIdentifier: '',
  batteryMaterialMass: 0,
  isCriticalRawMaterial: false,
  batteryMaterialLocation: {componentName: '', componentId: ''}
}) // 材料组成 - 有害物质列配置
const substanceColumns = ref([
  {prop: 'hazardousSubstanceName', label: t('物质名称'), type: 'input'},
  {prop: 'hazardousSubstanceClass', label: t('物质类别'), type: 'select', options: hazardousSubstanceClassType},
  {prop: 'hazardousSubstanceConcentration',label: t('浓度(%)'),type: 'input-number',min: 0,max: 100,precision: 2},
  {prop: 'hazardousSubstanceImpact', label: t('影响'), type: 'select', multiple: true, options: ExtinguishingAgentType},
  {
    prop: 'hazardousSubstanceLocation',
    label: t('所在组件'),
    type: 'complex',
    children: [
      {prop: 'componentName', placeholder: t('组件名称'), type: 'input'},
      {prop: 'componentId',placeholder: t('组件ID'),type: 'input'}]
  },
  {prop: 'hazardousSubstanceIdentifier', label: t('物质标识符'), type: 'input'}
])
const defaultSubstance = ref({
  hazardousSubstanceName: '',
  hazardousSubstanceClass: '',
  hazardousSubstanceConcentration: 0,
  hazardousSubstanceImpact: [],
  hazardousSubstanceLocation: {componentName: '', componentId: ''},
  hazardousSubstanceIdentifier: ''
}) // 碳足迹 - 生命周期阶段列配置
const stageColumns = ref([
  {prop: 'lifecycleStage', label: t('生命周期阶段'), type: 'select', options: LifecycleStage},
  {prop: 'carbonFootprint', label: t('碳足迹(kg CO2e)'), type: 'input-number', min: 0, precision: 2}
])
const defaultStage = ref({lifecycleStage: '', carbonFootprint: 0}) // 性能数据 - 功率能力列配置
const powerCapabilityColumns = ref([
  {prop: 'atSoC',label: t('SoC(%)'),type: 'input-number',min: 0,max: 100},
  {prop: 'powerCapabilityAt', label: t('功率能力(kW)'), type: 'input-number', min: 0, precision: 2}
])
const defaultPowerCapability = ref({ atSoC: 0, powerCapabilityAt: 0}) // 性能数据 - 内阻列配置
const resistanceColumns = ref([
  {prop: 'ohmicResistance', label: t('欧姆电阻(Ω)'), type: 'input-number', min: 0, precision: 4},
  {prop: 'batteryComponent', label: t('电池组件'), type: 'select', options: BatteryComponent}])
const defaultResistance = ref({ohmicResistance: 0, batteryComponent: ''}) // 性能数据 - 负面事件列配置
const negativeEventColumns = ref([
  {prop: 'negativeEvent', label: t('负面事件'), type: 'input'},
  {prop: 'lastUpdate', label: t('最后更新时间'), type: 'datetime'}
])
const defaultNegativeEvent = ref({negativeEvent: '', lastUpdate: ''}) // 循环信息 - 文档列配置
const documentColumns = ref([
  {prop: 'documentType', label: t('文档类型'), type: 'select', options: DocumentType},
  {prop: 'mimeType', label: t('MIME类型'), type: 'input', placeholder: t('例如: application/pdf')},
  {prop: 'documentURL', label: t('文档URL'), type: 'input', placeholder: t('文档URL'), component: 'file'}])
const defaultDocument = ref({documentType: '', mimeType: '', documentURL: ''}) // 循环信息 - 供应商列配置
const supplierColumns = ref([
  {prop: 'nameOfSupplier', label: t('供应商名称'), type: 'input'},
  {
    prop: 'addressOfSupplier',
    label: t('供应商地址'),
    type: 'complex',
    children: [
      {prop: 'addressCountry', placeholder: t('国家'), type: 'input'},
      {prop: 'streetAddress', placeholder: t('街道地址'), type: 'input'},
      {prop: 'postalCode', placeholder: t('邮编'), type: 'input'}]
  },
  {
    prop: 'contactInfo',
    label: t('联系方式'),
    type: 'complex',
    children: [
      {prop: 'emailAddressOfSupplier', type: 'email'},
      {prop: 'supplierWebAddress', placeholder: t('网站'), type: 'input'}]
  },
  {
    prop: 'components',
    label: t('部件列表'),
    type: 'table',
    columns: [
      {prop: 'partName', label: t('部件名称'), type: 'input'},
      {prop: 'partNumber', label: t('部件编号'), type: 'input'}
    ],
    defaultItem: {partName: '', partNumber: ''}
  }
])
const defaultSupplier = ref({
  nameOfSupplier: '',
  addressOfSupplier: {streetAddress: '', postalCode: '', addressCountry: ''},
  emailAddressOfSupplier: '',
  supplierWebAddress: '',
  components: []
}) // 循环信息 - 回收内容列配置
const recycledContentColumns = ref([
  {prop: 'recycledMaterial', label: t('回收材料'), type: 'select', options: RecycledMaterialType},
  {prop: 'preConsumerShare', label: t('消费前份额(%)'), type: 'input-number', min: 0, max: 100},
  {prop: 'postConsumerShare', label: t('消费后份额(%)'), type: 'input-number', min: 0, max: 100}
])
const defaultRecycledContent = ref({recycledMaterial: '', preConsumerShare: 0, postConsumerShare: 0})

const isCreate = computed(() => route.path.includes('/create'))

const fetchData = async () => {
  if (isCreate.value) return loading.value = true
  try {
    const res = await batteryPassportApi.getBatteryPassportById(route.params.id)
    if (res.code !== 200) {
      ElMessage.error(res.message)
      return
    }
    formData.value = res.data
  } catch (error) {
    console.error(t('获取电池护照详情失败:'), error)
  } finally {
    loading.value = false
  }
}
const submitForm = async () => {
  try {
    loading.value = true
    const valid = await formRef.value.validate()
    if (!valid) return
    if (isCreate.value) {
      const res = await batteryPassportApi.createBatteryPassport(formData.value)
      if (res.code !== 200) {
        ElMessage.error(t('创建失败'))
      }
      ElMessage.success(t('创建成功'))
      await router.push({
        name: batteryPassportDetail,
        params: {
          id: res.data  // 参数名需与路由配置中的 :id 匹配
        }
      })
    } else {
      const res = await batteryPassportApi.updateBatteryPassport(route.params.id, formData.value)
      if (res.code !== 200 && res.data) {
        ElMessage.error(t('更新失败'))
      }
      ElMessage.success(t('更新成功'))
      router.push({
        name: batteryPassportDetail,
        params: {
          id: route.params.id  // 参数名需与路由配置中的 :id 匹配
        }
      })
    }
  } catch (error) {
    ElMessage.error(t('保存失败'))
  } finally {
    loading.value = false
  }
}
const goBack = () => {
  router.go(-1)
}
onMounted(() => {
  fetchData()
})

</script>
<style scoped>
@reference "tailwindcss";

/* 可以添加一些自定义样式

*/
:deep(.el-collapse) {
}

:deep(.el-collapse-item) {
}
:deep(.el-form-item__label) {
  @apply w-64;
}
:deep(.el-collapse-item__header) {
  @apply p-4 text-lg;
}
:deep(.el-collapse-item__content) {
  @apply py-4 px-8;
}


</style>